<template>
  <div class="login">
    <div class="title">
      <div class="welcome">欢迎登录</div>
      <div class="name">无人机在线管理系统</div>
    </div>
    <el-form
      ref="loginRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <div class="logo"></div>
      <div class="form-content">
        <div class="contentInfo">
          <div class="contentInfo-text">用户名</div>
          <el-form-item prop="username" style="margin-top: 2%">
            <el-input
              v-model="loginForm.username"
              type="text"
              size="large"
              auto-complete="off"
              placeholder="账号"
            >
              <template #prefix
                ><img src="/img/cockpit/user.png" alt=""
              /></template>
            </el-input>
          </el-form-item>
        </div>
        <div class="contentInfo">
          <div class="contentInfo-text">密码</div>
          <el-form-item prop="password" style="margin-top: 2%">
            <el-input
              v-model="loginForm.password"
              type="password"
              size="large"
              :show-password="true"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter="handleLogin"
            >
              <template #prefix
                ><img src="/img/cockpit/pwd.png" alt=""
              /></template>
              <!-- <template #suffix><img src="/img/cockpit/pwd.png" alt="" /></template> -->
            </el-input>
          </el-form-item>
        </div>
        <div class="contentInfo" v-if="passwordCodeShow">
          <div class="contentInfo-text">验证码</div>
          <el-form-item
            prop="code"
            v-if="captchaEnabled"
            style="margin-top: 2%"
          >
            <el-input
              v-model="loginForm.code"
              size="large"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter="handleLogin"
            >
              <template #prefix
                ><img src="/img/cockpit/yanzheng.png" alt=""
              /></template>
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>
        </div>
<!--        <el-form-item prop="sms" v-if="captchaEnabled">-->
<!--          <el-input-->
<!--            v-model="loginForm.sms"-->
<!--            size="large"-->
<!--            auto-complete="off"-->
<!--            placeholder="6位短信验证码"-->
<!--            style="width: 63%"-->
<!--            @keyup.enter="handleLogin"-->
<!--          >-->
<!--            <template #prefix-->
<!--              ><img src="/img/cockpit/yanzheng.png" alt=""-->
<!--            /></template>-->
<!--          </el-input>-->
<!--          <div class="obtain-code" @click="getSMSCode">获取验证码</div>-->
<!--        </el-form-item>-->
        <div class="forgetPassword" @click="passwordMouse">忘记密码</div>
        <el-form-item style="margin-top: 11%">
          <el-button
            :loading="loading"
            size="large"
            type="primary"
            style="width: 100%"
            class="loginBtn"
            @click.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right" v-if="register">
            <router-link class="link-type" :to="'/register'"
              >立即注册</router-link
            >
          </div>
        </el-form-item>
      </div>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2023 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
import {
  getCodeImg,
  getSmsByUsername,
  login,
  experimentLogin,
} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";
import { onMounted } from "vue";
import { setToken } from "@/utils/auth";

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const passwordCodeShow = ref(true);
const count = ref(0);
const token = ref("");

const loginForm = ref({
  username: "admin",
  password: "admin123",
  // sms: "",
  // code: "",
  // uuid: "",
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "用户名不能为空" }],
  password: [{ required: true, trigger: "blur", message: "密码不能为空" }],
  code: [{ required: true, trigger: "change", message: "图形验证码不能为空" }],
  sms: [{ required: true, trigger: "change", message: "短信验证码不能为空" }],
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

function handleLogin() {
  proxy.$refs.loginRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // if (count.value < 2) {
      //   loginAgain();
      // } else {
        experimentLoginFun();
      // }
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      // if (loginForm.value.rememberMe) {
      //   Cookies.set("username", loginForm.value.username, { expires: 30 });
      //   Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
      //   Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      // } else {
      //   // 否则移除
      //   Cookies.remove("username");
      //   Cookies.remove("password");
      //   Cookies.remove("rememberMe");
      // }
    }
  });
}

function experimentLoginFun() {
  // 调用action的登录方法
  new Promise((resolve, reject) => {
    experimentLogin(loginForm.value)
      .then((res) => {
        let data = res.data;
        setToken(data.access_token);
        token.value = data.access_token;
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
        resolve();
      })
      .catch((error) => {
        loading.value = false;
        // // 重新获取验证码
        // if (captchaEnabled.value) {
        //   getCode();
        // }
        reject(error);
      });
  });
}

function loginAgain() {
  delete loginForm.value.uuid;
  // 调用action的登录方法
  new Promise((resolve, reject) => {
    login(loginForm.value)
      .then((res) => {
        let data = res.data;
        setToken(data.access_token);
        // token.value = data.access_token
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
        resolve();
      })
      .catch((error) => {
        count.value++;
        if (count.value > 1) {
          passwordCodeShow.value = true;
          getCode();
        }
        loading.value = false;
      });
  });
}

function getCode() {
  getCodeImg().then((res) => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value['uuid'] = res.uuid;
    }
  });
}

// 获取短信验证
function getSMSCode() {
  console.log(loginForm.value.username);
  getSmsByUsername({ username: loginForm.value.username }).then((response) => {
    console.log(response);
  });
}

function passwordMouse() {
  proxy.$modal.msgSuccess("请联系管理员重置密码");
}

onMounted(() => {
  getCode();
});
</script>

<style lang="scss">
.login {
  .el-input,
  .el-input__wrapper {
    border: none !important;
    box-shadow: none !important;
  }
}
</style>

<style lang="scss" scoped>
.login {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("/img/cockpit/login.png");
  background-size: 100% 100%;
}
.title {
  position: absolute;
  top: 23.8%;
  left: 23.1%;

  .welcome {
    font-size: 44px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #ffffff;
  }

  .name {
    font-size: 36px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #ffffff;
  }
}

.login-form {
  position: absolute;
  top: 15.4%;
  right: 17.7%;
  padding: 0 6.5%;
  //background: #ffffff;
  width: 32.3%;
  height: 69.4%;
  display: flex;
  flex-direction: column;
  justify-content: center;

  .logo {
    width: 308px;
    height: 77px;
    margin: 0 auto 34px;
    background: url("@/assets/manager/companyLogo.png");
  }

  .form-content {
    top: 21.5%;
    left: 21%;
    width: 100%;

    .contentInfo {
      height: 72px;
      display: flex;
      flex-direction: column;
      margin-bottom: 20px;

      .contentInfo-text {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
      }
    }
  }

  :deep .el-form-item {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    border: 1px solid #ebebeb;
    border: 1px solid #ebebeb;
    border-radius: 4px;
  }

  :deep .el-form-item__content {
    height: 48px;
  }

  .el-input {
    flex: 1;
  }

  .loginBtn {
    width: 100%;
    height: 60px;
    background: #0fc17c;
    border-radius: 10px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 29.4%;
  min-width: 108px;
  height: 48px;
  padding-left: 0;

  img {
    width: 100%;
    height: 100%;
    padding-left: 0;
    cursor: pointer;
    vertical-align: middle;
  }
}
.obtain-code {
  width: 29.4%;
  min-width: 108px;
  height: 40px;
  text-align: center;
  cursor: pointer;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #0fc17c;
  border-left: 1px solid #ebebeb;
}
.forgetPassword {
  // position: absolute;
  // left: 0;
  // top: 65.7%;
  color: #0fc17c;
  height: 14px;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #0fc17c;
  cursor: pointer;
  transform: translateY(-10%);
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
// .login-code-img {
//   height: 40px;
//   min-width: 106px;
//   // padding-left: 12px;
// }

:deep .el-form-item__content {
  display: flex;
  justify-content: space-between;
}
</style>
